import os
import numpy as np
import librosa
import json
import csv
from speech_analyzer import SpeechAnalyzer

def simulate_speech_frames(total_frames, speech_frames_ratio, sr=22050, frame_length=2048):
    """
    模拟不同语速特性的语音帧数据
    
    参数:
    - total_frames: 总帧数
    - speech_frames_ratio: 语音帧比例 (0-1), 表示语音密度
    - sr: 采样率
    - frame_length: 帧长度
    
    返回:
    - 模拟语音数据
    - 语音帧数据
    """
    # 创建一段固定时长的模拟音频
    duration = 20  # 20秒音频
    y = np.zeros(sr * duration)
    
    # 随机在音频中添加一些"语音信号"
    speech_frames_count = int(total_frames * speech_frames_ratio)
    
    # 生成模拟语音帧数据
    frames_data = []
    
    # 为不同语速特性生成不同的帧数据
    for i in range(total_frames):
        is_speech = 1 if i < speech_frames_count else 0
        
        if is_speech:
            # 模拟有语音的帧
            pitch_value = 300 + 100 * np.sin(i * 0.2) + np.random.uniform(-50, 50)
            volume_value = 0.07 + 0.03 * np.sin(i * 0.3) + np.random.uniform(-0.01, 0.01)
        else:
            # 模拟无语音的帧
            pitch_value = 0
            volume_value = 0.01
        
        frames_data.append({
            'is_speech': is_speech,
            'pitch': pitch_value,
            'volume': max(0.005, volume_value)
        })
    
    return y, frames_data

def test_with_simulated_data():
    """使用模拟数据测试语速检测算法"""
    # 创建不同语速特性的模拟数据
    test_scenarios = [
        {"name": "慢语速", "frames": 100, "speech_ratio": 0.3},
        {"name": "中等语速", "frames": 100, "speech_ratio": 0.6},
        {"name": "快语速", "frames": 100, "speech_ratio": 0.9}
    ]
    
    print("\n==== 模拟不同语速场景测试 ====\n")
    
    analyzer = SpeechAnalyzer()
    
    # 测试每个场景
    for scenario in test_scenarios:
        print(f"\n--- 测试场景: {scenario['name']} ---")
        
        # 生成模拟数据
        audio_data, frames_data = simulate_speech_frames(
            scenario['frames'], 
            scenario['speech_ratio']
        )
        
        # 直接调用分析函数，跳过文件IO
        speech_rate, speech_rate_score = analyzer._calculate_speech_rate(
            frames_data, 
            audio_data, 
            sr=22050
        )
        
        print(f"语速 (词/秒): {speech_rate:.4f}")
        print(f"语速评分: {speech_rate_score:.4f}")
        
        # 将帧数据写入CSV用于可视化
        output_dir = f"test_results/{scenario['name']}"
        os.makedirs(output_dir, exist_ok=True)
        
        with open(f"{output_dir}/frames.csv", 'w', newline='') as f:
            writer = csv.DictWriter(f, fieldnames=['is_speech', 'pitch', 'volume'])
            writer.writeheader()
            for frame in frames_data:
                writer.writerow(frame)
        
        # 保存带语速信息的结果
        with open(f"{output_dir}/results.json", 'w') as f:
            json.dump({
                "scenario": scenario['name'],
                "frames": scenario['frames'],
                "speech_ratio": scenario['speech_ratio'],
                "speech_rate": speech_rate,
                "speech_rate_score": speech_rate_score
            }, f, indent=2)
    
    # 比较结果
    print("\n==== 不同语速场景比较 ====")
    for scenario in test_scenarios:
        try:
            with open(f"test_results/{scenario['name']}/results.json", 'r') as f:
                data = json.load(f)
                print(f"{data['scenario']}: 语速 = {data['speech_rate']:.4f}, 评分 = {data['speech_rate_score']:.4f}")
        except:
            print(f"{scenario['name']}: 数据不可用")

if __name__ == "__main__":
    # 添加SpeechAnalyzer中需要的方法，如果原类中没有的话
    if not hasattr(SpeechAnalyzer, '_calculate_speech_rate'):
        def _calculate_speech_rate(self, frames_data, y, sr=22050):
            """计算语速和评分"""
            speech_frames = [f for f in frames_data if f['is_speech'] == 1]
            
            total_duration = len(y) / sr if len(y) > 0 else 0
            if total_duration > 0 and len(speech_frames) > 0:
                # 计算语音帧的比例
                speech_ratio = len(speech_frames) / len(frames_data) if len(frames_data) > 0 else 0
                
                # 计算每秒语音帧数（作为语速的直接指标）
                frames_per_second = len(speech_frames) / total_duration
                
                # 语速指标 - 根据经验值调整
                # 通常正常说话每秒约2-3个词，对应约8-15帧/秒
                # 将帧率转换为近似的词率
                word_rate_approx = frames_per_second / 5  # 假设平均每个词约5帧
                
                # 语速最终得分（词/秒）
                speech_rate = word_rate_approx
                
                # 确保有最小值
                speech_rate = max(0.5, speech_rate)
            else:
                speech_rate = 0
            
            # 语速得分 - 中等语速最佳（大约1.5-3.5词/秒）
            if speech_rate < 1.5:
                # 太慢的语速，但仍然给予基础分
                speech_rate_score = max(0.4, speech_rate / 1.5)
            elif speech_rate > 3.5:
                # 太快的语速，但惩罚更温和
                speech_rate_score = max(0.5, 1 - (speech_rate - 3.5) / 2.0)
            else:
                # 理想语速范围
                speech_rate_score = 1.0
                
            return speech_rate, speech_rate_score
            
        SpeechAnalyzer._calculate_speech_rate = _calculate_speech_rate
    
    # 运行模拟测试
    test_with_simulated_data()
